<template>
  <list-template>
    <template slot="header">
      <el-form class="search-form" :model="searchData" ref="searchForm"  inline>
        <slot name="condition"></slot>
        <el-form-item v-if="$scopedSlots.condition">
          <el-button
            class="filter-item"
            type="primary"
            v-waves
            icon="el-icon-search"
            @click="changeCondition"
          >搜索</el-button>
        </el-form-item>
        <el-form-item v-if="$scopedSlots.condition">
          <el-button class="filter-item" v-waves icon="el-icon-delete" @click="clearSearch">清除</el-button>
        </el-form-item>
      </el-form>
      <el-form class="list-operation"  inline>
        <el-row type="flex" justify="space-between">
          <!-- <el-col> -->
          <slot name="normalOperation"></slot>
          <!-- </el-col>
          <el-col>-->
          <slot name="batchOperation"></slot>
          <!-- </el-col> -->
        </el-row>
      </el-form>
    </template>
    <template slot="main" slot-scope="props">
      <el-table
        ref="dataTable"
        border
        fit

        style="width: 100%"
        :highlight-current-row="highlightCurrentRow"
        :stripe="stripe"
        :height="tableHeight || props.clientHeight"
        :data="rows"
        :default-sort="defaultSort"
        :row-class-name="rowClassName"
        :cell-class-name="cellClassName"
        @sort-change="handleSortChange"
        @current-change="handleSelectionChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column v-if="batchColumn" type="selection" :width="35"></el-table-column>
        <el-table-column
          v-if="indexColumn"
          type="index"
          width="50"
          :index="rowIndex"
          align="center"
        ></el-table-column>
        <el-table-column v-if="multipleSelected" type="selection" width="50" align="center"></el-table-column>
        <slot name="columns"></slot>
        <template v-for="columnHeader in columns">
          <el-table-column
            v-if="columnHeader.customer"
            :key="columnHeader.prop"
            :prop="columnHeader.prop"
            :label="columnHeader.label"
            :min-width="columnHeader.minWidth || ''"
            :width="columnHeader.width || ''"
            :header-align="columnHeader.headerAlign || 'center'"
            :align="columnHeader.align || 'center'"
          >
            <template slot-scope="scope">
              <component
                v-for="(actionItem,index) in columnHeader.customer"
                :key="index"
                :data="scope"
                :is="actionItem"
              ></component>
            </template>
          </el-table-column>
          <el-table-column
            v-else
            :key="columnHeader.prop"
            :sortable="columnHeader.sortable || false"
            :prop="columnHeader.prop"
            :formatter="columnHeader.formatter"
            :label="columnHeader.label"
            :min-width="columnHeader.minWidth || ''"
            :width="columnHeader.width || ''"
            :header-align="columnHeader.headerAlign || 'center'"
            :align="columnHeader.align || 'center'"
          ></el-table-column>
        </template>
      </el-table>
    </template>
    <template slot="footer">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange"
        :current-page.sync="pageInfo.pageIndex"
        :page-size.sync="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper "
        :total="total"
      ></el-pagination>
    </template>
    <slot></slot>
  </list-template>
</template>

<script>
import { getSort } from '@/utils/paged'
import ListTemplate from '@/components/templates/listTemplate'
export default {
  components: {
    ListTemplate
  },
  /**
   * 输入参数
   */
  props: {
    /**
     * 列
     */
    columns: {
      type: Array,
      default: function () {
        return []
      }
    },
    /**
     * 是否多选
     */
    multipleSelected: {
      type: Boolean,
      default: false
    },
    batchColumn: {
      type: Boolean,
      default: false
    },
    /**
     * 是否包含索引列
     */
    indexColumn: {
      type: Boolean,
      default: false
    },
    /**
     * 数据行
     */
    rows: {
      type: Array,
      default: function () {
        return []
      }
    },
    highlightCurrentRow: {
      type: Boolean,
      default: true
    },
    stripe: {
      type: Boolean,
      default: true
    },
    /**
     * 数据总数
     */
    total: {
      type: Number,
      default: 0
    },
    /**
     * 默认分页配置
     */
    pageSize: {
      type: Object,
      default: function () {
        return {
          default: 20,
          size: [10, 20, 30, 50]
        }
      }
    },
    /**
     * 行样式名称
     */
    rowClassName: {
      type: Function,
      default: null
    },

    cellClassName: {
      type: Function,
      default: null
    },
    /**
     * 记住选择，在multipleSelected为true时可用
     */
    remberSelection: {
      type: Boolean,
      default: false
    },
    /**
     * 数据行的键
     */
    dataKey: {
      type: String
    },
    /**
     * 表格高度
     */
    tableHeight: {
      type: Number,
      default: 0
    },
    /**
     * 默认排序
     */
    defaultSort: {
      type: Object
    },

    /**
     * 筛选数据
     */
    searchData: {
      type: Object
    }
  },
  watch: {
    /**
     * 监控数据变化
     * @param  {Array} newRows 新数据
     * @param  {Array} oldRows 原数据
     */
    rows (newRows, oldRows) {
      if (
        Array.isArray(newRows) &&
        newRows.length > 0 &&
        this.multipleSelected &&
        this.remberSelection
      ) {
        var selectedRows = this.remberRows[`page_${this.pageInfo.pageIndex}`]
        if (Array.isArray(selectedRows) && selectedRows.length > 0) {
          /**
           * 选中记住的行
           */
          for (var i = 0; i < newRows.length; i++) {
            var row = newRows[i]
            if (
              selectedRows.find(sr => sr[this.dataKey] === row[this.dataKey])
            ) {
              this.$refs.dataTable.toggleRowSelection(row)
            }
          }
          /**
           * 移除已不存在的行
           */
          this.remberRows[
            `page_${this.pageInfo.pageIndex}`
          ] = selectedRows.filter(sr => {
            return (
              newRows.find(nr => nr[this.dataKey] === sr[this.dataKey]) !==
              undefined
            )
          })
        }
      }
    }
  },
  data () {
    return {
      pageInfo: {
        pageIndex: 1,
        pageSize: this.pageSize.default,
        orders: []
      },
      size: this.pageSize.size,
      selectedRows: [],
      remberRows: {}
    }
  },
  methods: {
    clearSearch () {
      this.$refs.searchForm.resetFields()
      this.changeCondition()
    },
    /**
     * 清除多选
     */
    clearSelection () {
      this.$refs.dataTable.clearSelection()
    },
    /**
     * 设置某一行的选中状态
     */
    toggleRowSelection (row, selected) {
      this.$refs.dataTable.toggleRowSelection(row, selected)
    },
    /**
     * 行选中事件处理
     * @param {*} rows 行数据
     */
    handleSelectionChange (rows) {
      if (this.multipleSelected && this.remberRows) {
        this.remberRows[`page_${this.pageInfo.pageIndex}`] = rows
      }
      this.selectedRows = rows
      this.onSelected()
    },
    /**
     * 处理排序信息变化事件
     * @param {*} sort 排序信息
     */
    handleSortChange (sort) {
      this.pageInfo.orders = []
      if (sort.order) {
        this.pageInfo.orders.push(getSort(sort))
      }
      this.pageInfo.pageIndex = 1
      this.remberRows = {}
      this.onPageInfoChange()
    },
    /**
     * 处理分页大小变化事件
     * @param {*} size 分页大小
     */
    handlePageSizeChange (size) {
      this.pageInfo.pageSize = size
      this.pageInfo.pageIndex = 1
      this.remberRows = {}
      this.onPageInfoChange()
    },
    /**
     * 处理页码变化事件
     * @param {*} currentPage 页码
     */
    handlePageCurrentChange (currentPage) {
      this.pageInfo.pageIndex = currentPage
      this.onPageInfoChange()
    },
    /**
     * 外部条件变化时处理
     */
    handleConditionChange () {
      this.resetTable()
      this.onPageInfoChange()
    },
    /**
     * 触发分页信息变化事件
     */
    onPageInfoChange () {
      this.$emit('page-info-change', this.pageInfo)
    },
    /**
     * 触发数据选中事件
     */
    onSelected () {
      var rows
      if (!this.multipleSelected || !this.remberSelection) {
        rows = this.selectedRows
      } else {
        rows = {
          currentPageRows: this.selectedRows,
          allRows: Object.values(this.remberRows).reduce(
            (all, value) => Array.from(new Set(all.concat(value))),
            []
          )
        }
      }
      this.$emit('selected', rows)
    },
    /**
     * 计算序号
     * @param {*} index 参数
     */
    rowIndex (index) {
      return this.pageInfo.pageSize * (this.pageInfo.pageIndex - 1) + index + 1
    },
    /**
     * 重置条件并触发条件变化事件
     */
    changeCondition () {
      this.handleConditionChange()
    },
    /**
     * 重置当前页
     */
    reloadCurrent () {
      this.onPageInfoChange()
    },
    /**
     * 重置表格排序、分页、内容
     */
    resetTable () {
      this.pageInfo.pageIndex = 1
      // this.pageInfo.orders = []
      // this.$refs.dataTable.clearSort()
      this.remberRows = {}
    }
  },
  created () {
    if (this.defaultSort) {
      this.pageInfo.orders.push(getSort(this.defaultSort))
    }
    this.pageInfo.pageSize = this.pageSize.default
    this.size = this.pageSize.size
    this.onPageInfoChange()
  }
}
</script>
